package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.PublicMilestone;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.MilestoneGetResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.model.UIPublicMilestone;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.PublicMilestoneAdapter;

import org.lucasr.twowayview.ItemClickSupport;
import org.lucasr.twowayview.widget.DividerItemDecoration;
import org.lucasr.twowayview.widget.TwoWayView;

import java.util.ArrayList;

public class TimelineMilestoneActivity extends BaseActivity implements ItemClickSupport.OnItemClickListener, CuteToolbar.OnClickCuteToolbarListener {

    private static final int SPAN_COUNT = 5;

    private CuteEditText mTextInput;

    private PublicMilestoneAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline_milestone);
        setupLayout();
        queryMilestone(true);
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View view, int i, long l) {
        if (mAdapter.onItemClick(i)) {
            if (!TextUtils.isEmpty(mAdapter.getSelect().getExtra())) {
                mTextInput.setText(mAdapter.getSelect().getExtra() + mAdapter.getSelect().getValue());
            } else {
                mTextInput.setText(mAdapter.getSelect().getValue());
            }
        }
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {
        sendMilestone(null);
    }

    // 发送 第一次
    public void sendMilestone(View v) {
        String content = mTextInput.getText().toString();
        if (TextUtils.isEmpty(content)) {
            tipShow("请选择里程碑");
            return;
        }
        UIPublicMilestone milestone = mAdapter.getSelect();
        if (milestone == null) {
            result(-1, mTextInput.getText().toString());
            return;
        }
        String extra = milestone.getExtra();
        String value = milestone.getValue();
        if (TextUtils.isEmpty(extra)) {
            checkResult(value, content);
        } else {
            checkResult(extra + value, content);
        }
    }

    private void setupLayout() {
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        mTextInput = (CuteEditText) findViewById(R.id.edit_milestone);
        TwoWayView recyclerView = (TwoWayView) findViewById(R.id.recycler_milestone);
        mAdapter = new PublicMilestoneAdapter();
        final Drawable divider = getResources().getDrawable(R.drawable.divider);
        recyclerView.addItemDecoration(new DividerItemDecoration(divider));
        recyclerView.setAdapter(mAdapter);
        final ItemClickSupport itemClick = ItemClickSupport.addTo(recyclerView);
        itemClick.setOnItemClickListener(this);
    }

    private void queryMilestone(boolean request) {
        PublicMilestone[] publicMilestones = DatabaseManager.getInstance(this).queryPublicMilestone();
        if (publicMilestones != null && publicMilestones.length > 0) {
            updateUI(publicMilestones);
        } else {
            if (request) {
                request();
            }
        }
    }

    private void updateUI(PublicMilestone[] publicMilestones) {
        ArrayList<UIPublicMilestone> list = new ArrayList<UIPublicMilestone>();
        int type = publicMilestones[0].getType();
        addTitle(type, list);
        int baseTypeLength = 1;
        for (PublicMilestone publicMilestone : publicMilestones) {
            if (type != publicMilestone.getType()) {
                addEmpty(type, list, baseTypeLength);
                baseTypeLength++;
                type = publicMilestone.getType();
                addTitle(type, list);
            }
            UIPublicMilestone timelineMilestone = new UIPublicMilestone();
            timelineMilestone.setBaseType(UIPublicMilestone.BASE_TYPE_VALUE);
            timelineMilestone.setType(publicMilestone.getType());
            timelineMilestone.setId(publicMilestone.getMilestoneID());
            timelineMilestone.setValue(publicMilestone.getMilestone());
            if (publicMilestone.getType() != UIPublicMilestone.TYPE_1) {
                timelineMilestone.setExtra("第一次");
            }
            list.add(timelineMilestone);
        }
        addEmpty(type, list, baseTypeLength);
        mAdapter.setList(list);
    }

    private void request() {
        LoginInfo login = Config.getLoginInfo(this);
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
        Client.requestMilestoneGet(this, phone, token, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                super.onInnovationStart();
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                MilestoneGetResponse response = get(value.toString(), MilestoneGetResponse.class);
                insertMilestone(response);
                queryMilestone(false);
            }

            @Override
            public void onChZhRJFailure(String value) {
                super.onChZhRJFailure(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                super.onChZhRJTokenFailure(value);
            }

        }, networkUnavailableSampleImpl());
    }

    private void insertMilestone(MilestoneGetResponse response) {
        DatabaseManager.getInstance(this).insertPublicMilestone(response);
    }

    private void addTitle(int type, ArrayList<UIPublicMilestone> list) {
        UIPublicMilestone milestone = new UIPublicMilestone();
        milestone.setBaseType(UIPublicMilestone.BASE_TYPE_TITLE);
        milestone.setType(type);
        list.add(milestone);
    }

    private void addEmpty(int type, ArrayList<UIPublicMilestone> list, int baseTypeLength) {
        int createLength = SPAN_COUNT - (list.size() - baseTypeLength) % SPAN_COUNT;
        for (int k = 0; k < createLength; k++) {
            UIPublicMilestone timelineMilestone = new UIPublicMilestone();
            timelineMilestone.setBaseType(UIPublicMilestone.BASE_TYPE_VALUE);
            timelineMilestone.setType(type);
            list.add(timelineMilestone);
        }
    }

    private void result(int milestoneID, String milestone) {
        Intent returnIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt("milestoneID", milestoneID);
        bundle.putString("milestone", milestone);
        returnIntent.putExtras(bundle);
        setResult(RESULT_OK, returnIntent);
        finish();
    }

    private void checkResult(String value, String content) {
        if (value.equals(content)) {
            result(mAdapter.getSelect().getId(), value);
        } else {
            result(-1, content);
        }
    }
}
